package com.lagou.framework.interceptor;

import com.lagou.edu.controller.DemoController;
import com.lagou.framework.annotation.Security;
import com.lagou.framework.mvc.MethodHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 通过preHandler进行人员权限过滤
 *
 * @author srh
 * @date 2020/03/19
 **/
public class AccountSecurityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandler(HttpServletRequest request, MethodHandler handler) {
        String reqAccountName = request.getParameter(DemoController.USERNAME);
        Set<String> accountNames = getAllowAccountNames(handler);
        return accountNames.contains(reqAccountName);
    }

    private Set<String> getAllowAccountNames(MethodHandler handler) {
        Set<String> accountNames = new HashSet<>();
        Security clazz = handler.getInstance().getClass().getAnnotation(Security.class);
        if (null != clazz) {
            accountNames.addAll(Stream.of(clazz.value()).collect(Collectors.toSet()));
        }
        Security method = handler.getMethod().getAnnotation(Security.class);
        if (null != method) {
            accountNames.addAll(Stream.of(method.value()).collect(Collectors.toSet()));
        }
        return accountNames;
    }
}
